define(function () {
    return function (pane) {
        /**
         * 导航
         */
        {
            pane.html(utils.getHtml('default_table'));

            utils.addFilterGroupbtn(pane, {
                name: 'status',
                text: '全部状态',
                filters: dicts.withdraw_status
            });
        }

        /**
         * 统计
         */
        {
            var analyse = function () {
                adminApi('withdraws_analyse').then(function (rows) {
                    $('.content-header .filter-status[data-name="status"] .badge').text('');
                    var total = 0;
                    for (var i in rows) {
                        var row = rows[i];
                        $('.status-' + row.status, pane).text((row.count || 0) + '个, ' + (row.amount ? row.amount.toFixed(2) : 0));
                        total += (row.count || 0);
                    }
                    $('.status-all', pane).text(total);
                });
            }
            analyse();
        }

        //初始化工具
        utils.addTools(pane, [
            {className: 'refresh-btn', icon: 'fa-refresh', text: '刷新'}
        ]);
        $(pane).on('click', '.refresh-btn', function () {
            if (table) {
                table.api().draw();
            }
            analyse();
        });

        //初始化表格
        var table = utils.dataTable(pane, {
            columns_arrays: [
                ["id", "#"],
                ["partner_id", "合伙人", false, function (i, t, row) {
                    var user = row.partner_user;
                    if (!user) {
                        return '';
                    }
                    return (user.image ? '<img src="' + user.image + '?imageView2/1/w/150/h/150/q/75"> ' : '') + '<div>' + (user.nickname || user.tel) + '</div><div>「ID:' + (user.id) + '」</div>';
                }, 'filterable'],
                ["user_id", "账户", false, function (s, t, row) {
                    var user = row.user;
                    if (!user) {
                        return '';
                    }
                    return (user.image ? '<img src="' + user.image + '?imageView2/1/w/150/h/150/q/75"> ' : '') + '<div>' + (user.nickname || user.tel) + '</div><div>「ID:' + (user.id) + '」</div>';
                }, 'filterable'],
                ["user_id", "用户", false, function (s, t, row) {
                    var user = row.user;
                    if (!user) {
                        return '';
                    }
                    return '<div>' + utils.dictValue('user_level', user.level) + '</div>' +
                        '<div>余额:<span class="badge finances-opt" style="background-color: #00a65a!important; cursor: pointer;">￥' + user.amount + '</span></div>' +
                        '<div>冻结:<span class="badge finances-opt" style="background-color: #f39c12!important; cursor: pointer;">￥' + user.frozen + '</span></div>' +
                        (user.order_count ? '<div>总订单数:<span class="badge orders-opt" style="background-color: #3c8dbc!important; cursor: pointer;">' + user.order_count + '</span></div>' : '') +
                        (user.finish_count ? '<div>完成数量:<span class="badge orders-opt" style="background-color: #3c8dbc!important; cursor: pointer;">' + user.finish_count + '</span></div>' : '') +
                        (user.sham_count ? '<div>欺诈数量:<span class="badge orders-opt" style="background-color: #dd4b39!important; cursor: pointer;">' + user.sham_count + '</span></div>' : '');
                }],
                ["trade_no", "交易号", false],
                ["total_amount", "金额", false, utils.priceRender()],
                ["charge", "手续费", false, utils.priceRender()],
                ["amount", "需付", false, utils.priceRender()],
                ["bank_type", "账户类型", false, utils.dictRender('bank_type')],
                ["bank_name", "账户名称", false],
                ["bank_no", "账户账号", false],
                ["bank_tel", "手机号", false, false, 'filterable'],
                ["note", "备注", false, utils.nameRender()],
                ["status", "状态", false, utils.dictRender('withdraw_status')],
                ["created_at", "创建时间", false, utils.dateTimeRender()]
            ],
            sorting: [[0, 'desc']],
            fnServerData: function (paramData) {
                return adminApi('withdraws_browse', paramData);
            }
        });

        //编辑开关
        var toggleHandler = utils.toggleChild(pane, 0, function (checked) {
            table.api().rows().every(function (idx) {
                var child = this.child, data = this.data();
                if (checked == 1) {
                    var opts = [];
                    if (data.status === 'Pending') {
                        opts.push({text: '支付成功', className: 'successful-opt btn-success'});
                        opts.push({text: '取消支付', className: 'cancel-opt btn-danger'});
                    }
                    opts.push({text: '编辑备注', className: 'edit-note-opt'});
                    child(utils.childWrapper(idx, opts, false)).show();
                } else {
                    child.hide();
                }
            });
        });

        var updateRow = function (idx, data) {
            return adminApi('withdraws_load', {id: data.id}).then(function (withdraw) {
                table.fnUpdate(withdraw, idx, undefined, false);
                toggleHandler();
                analyse();
            });
        }

        //初始化事件
        table.on('draw.dt', toggleHandler).on('click', '.edit-note-opt', utils.tableEvent(table, function (idx, rowData) {
            //编辑备注
            utils.formEdit(table, {
                name: '编辑备注 - ' + rowData.trade_no,
                fields: utils.convertFields([
                    ['note', 'textarea', '备注']
                ]),
                columns: 12,
                data: rowData,
                fnServerData: function (paramData) {
                    return adminApi('withdraws_edit_note', paramData);
                }
            });
        })).on('click', '.cancel-opt', utils.tableEvent(table, function (idx, rowData) {
            //取消支付
            utils.confirmation(this, {
                placement: 'left',
                optName: '取消支付',
                title: '你确定取消支付?',
                fnConfirm: function () {
                    return adminApi('withdraws_status', {id: rowData.id, status: 'Failed'}).then(function (result) {
                        updateRow(idx, rowData);
                        return result;
                    });
                }
            });
        })).on('click', '.successful-opt', utils.tableEvent(table, function (idx, rowData) {
            //支付成功
            utils.confirmation(this, {
                placement: 'left',
                optName: '支付成功',
                title: '你确定支付成功?',
                fnConfirm: function () {
                    return adminApi('withdraws_status', {id: rowData.id, status: 'Successful'}).then(function (result) {
                        updateRow(idx, rowData);
                        return result;
                    });
                }
            });
        })).on('click', '.finances-opt', utils.tableEvent(table, function (idx, rowData) {
            //资金流水
            var html = $(utils.getHtml('form_assign', {title: '资金流水 - ' + rowData.user.nickname}));
            html.addClass('modal-fullscreen');
            html.modal('show').on('hidden.bs.modal', function (e) {
                html.remove();
            });
            var financesTable = utils.dataTable(html, {
                columns_arrays: [
                    ["id", "#"],
                    ["order_id", "订单号/交易号", false, function (s, t, row) {
                        return '<div>' + (row.order_id || row.payment_no || '') + '</div>';
                    }],
                    ["amount", "金额/费用", false, utils.priceRender()],
                    ["type", "入/出", false, utils.dictRender('finance_type')],
                    ["operation", "操作", false, utils.dictRender('finance_operation')],
                    ["by", "方式", false],
                    ["status", "状态", false, utils.dictRender('finance_status')],
                    ["created_at", "创建时间", false, utils.dateTimeRender()]
                ],
                sorting: [[0, 'desc']],
                fnServerData: function (paramData) {
                    paramData.push({name: 'user_id', value: rowData.user_id});
                    return adminApi('finances_browse', paramData);
                }
            });
        })).on('click', '.orders-opt', utils.tableEvent(table, function (idx, rowData) {
            //订单列表
            var html = $(utils.getHtml('form_assign', {title: '订单列表 - ' + rowData.user.nickname}));
            html.addClass('modal-fullscreen');
            html.modal('show').on('hidden.bs.modal', function (e) {
                html.remove();
            });
            var ordersTable = utils.dataTable(html, {
                columns_arrays: [
                    ["id", "#"],
                    ["mediumId", "代理", false, function (i, t, row) {
                        var user = row.agency;
                        if (!user) {
                            return '';
                        }
                        return (user.image ? '<img src="' + user.image + '?imageView2/1/w/150/h/150/q/75"> ' : '') + '<div>' + (user.nickname || user.tel) + '</div><div>「ID:' + (user.id) + '」</div>';
                    }, 'filterable'],
                    ["user_id", "用户", false, function (i, t, row) {
                        var user = row.user;
                        if (!user) {
                            return '';
                        }
                        return (user.image ? '<img src="' + user.image + '?imageView2/1/w/150/h/150/q/75"> ' : '') + '<div>' + (user.nickname || user.tel) + '</div><div>「ID:' + (user.id) + '」</div>' + '<div>订单数: ' + user.order_count + '/' + user.finish_count + '/' + user.sham_count + '&nbsp;&nbsp;金额: ' + user.amount + '/' + user.frozen + '</div>';
                    }, 'filterable'],
                    ["pictUrl", "图片", false, utils.imageRender('')],
                    ["auctionId", "商品名", false, function (i, t, row) {
                        return '<div style="max-width: 160px;">' + (row.auctionTitle || '') + '</div>';
                    }, 'filterable'],
                    ["exNickName", "店铺", false, function (i, t, row) {
                        return '<div style="max-width: 160px;">' + (row.exShopTitle || '') + '</div>';
                    }, 'filterable'],
                    ["payStatus", "状态", false],
                    ["id", "返现状态", false, function (i, t, row) {
                        return '<div style="min-width: 150px;"><div>' + row.taobaoTradeParentId + '</div><div>付款金额:' + row.totalAlipayFeeString + '</div>' +
                            '<div>预估收入:￥' + row.feeString + '/' + row.discountAndSubsidyToString + '%</div>' +
                            '<div>返现状态:' + row.amount_status + '</div>' +
                            '<div>返现金额:<span class="badge" style="background-color: #00a65a!important; cursor: pointer;">￥' + (row.pay_amount || 0) + '</span></div>' +
                            '<div>邀请返现:<span class="badge" style="background-color: #f39c12!important; cursor: pointer;">￥' + (row.inviter_pay_amount || 0) + '</span></div>' +
                            '<div>代理收入:<span class="badge" style="background-color: #3c8dbc!important; cursor: pointer;">￥' + (row.agency_amount || 0 ) + '</span></div>' +
                            '<div>上级收入:<span class="badge" style="background-color: #3c8dbc!important; cursor: pointer;">￥' + (row.inviter_agency_amount || 0 ) + '</span></div>' +
                            '<div>预计收入:<span class="badge" style="background-color: #dd4b39!important; cursor: pointer;">￥' + (row.income || 0) + '</span></div></div>';
                    }],
                    ["mediumId", "媒体", false, function (i, t, row) {
                        return row.mediumName;
                    }, 'filterable'],
                    ["adPositionId", "广告位", false, function (i, t, row) {
                        return row.adPositionName;
                    }, 'filterable'],
                    ["createTime", "下单日期", true, utils.dateTimeRender()],
                    ["created_at", "创建日期", false, utils.dateTimeRender()]
                ],
                sorting: [[0, 'desc']],
                fnServerData: function (paramData) {
                    paramData.push({name: 'user_id', value: rowData.user_id});
                    return adminApi('orders_browse', paramData);
                }
            });
        }));
    }
});